<?php
/**
 * created by zzy
 * date: 2018/1/26 14:07
 */


namespace App\Api\Service\Message\Controllers;

use App\Eloquent\Ygt\DepartmentUser;
use App\Eloquent\Ygt\Product;
use App\Eloquent\Ygt\ProductFields;
use App\Eloquent\Ygt\Purchase;
use App\Eloquent\Ygt\PurchaseMaterial;
use App\Eloquent\Ygt\SellerCompany;
use App\Eloquent\Ygt\UserMessage;
use Framework\BaseClass\Api\Controller;
use App\Engine\Func;

class PurchaseController extends Controller
{
    public $userId          = 25;
    //发起采购
    public  function start()
    {
        $userId             = Func::getHeaderValueByName('userid',$this->userId);
        $userInfo           = DepartmentUser::getCurrentInfo($userId);
        $messageId          = request('message_id',0);
        if(!$userInfo || !$messageId)
        {
            xThrow( ERR_PARAMETER );
        }
        //消息内容
        $where              = ['id'=>$messageId];
        $message            = UserMessage::getInfo($where);
        if(!$message)
        {
            xThrow(ERR_UNKNOWN,'消息出错');
        }
        //消息关联的采购单
        //$foreignKey         = $message->foreign_key;
        $type               = $message->type;
        $typeId             = $message->type_id;
        $purchase           = Purchase::where('id',$typeId)->first();
        if(!$purchase)
        {
            xThrow(ERR_UNKNOWN,'采购单信息出错');
        }
        $purchaseId         = $purchase->id;
        //采购单交货日期
        $finishedDate       = $purchase->finished_date;
        //$purchaseNumber     = $purchase->purchase_number;
        if(is_null($finishedDate))
        {
            $finishedDate   = '';
        }
        //采购单关联的材料列表
        $productData        = $this->getPurchaseProductList($purchaseId);
        $lists              = $productData['lists'];
        $totalMoney         = $productData['total_money'];
        //26=>'采购订单',//'工厂采购员发起采购时给供应商发消息',
        //27=>'工单采购',//工厂采购员发起采购时给仓库发消息
        //28=>'工单采购',//工厂采购员发起采购时给财务发消息
        switch ($type)
        {
            case 26:
                break;
            case 27:
                //仓库不需要看到金额
                foreach ($lists as $key => $row){
                    $lists[$key]['price'] = '';
                    $lists[$key]['money'] = '';
                }
                break;
            case 28:
                break;
            default:
                xThrow(ERR_UNKNOWN);
        }
        $addressAddress     = '';
        $result             = [
            'type'=>$type,
            'lists'=>$lists,
            'total_money'=>$totalMoney,
            'finished_date'=>$finishedDate,
            'address_address'=>$addressAddress,
        ];
        return $result;
    }
    //验收入库
    public function in()
    {
        $userId             = Func::getHeaderValueByName('userid',$this->userId);
        $userInfo           = DepartmentUser::getCurrentInfo($userId);
        $messageId          = request('message_id',0);
        if(!$userInfo || !$messageId)
        {
            xThrow( ERR_PARAMETER );
        }
        //消息内容
        $where              = ['id'=>$messageId];
        $message            = UserMessage::getInfo($where);
        if(!$message)
        {
            xThrow(ERR_UNKNOWN,'消息出错');
        }
        //初始化一些信息
        $totalMoney         = '';
        //消息关联的采购单
        //$foreignKey         = $message->foreign_key;
        $type               = $message->type;
        $typeId             = $message->type_id;
        $purchase           = Purchase::where('id',$typeId)->first();
        if(!$purchase)
        {
            xThrow(ERR_UNKNOWN,'采购单信息出错');
        }
        $purchaseId         = $purchase->id;
        //采购单交货日期
        $finishedDate       = $purchase->finished_date;
        $purchaseNumber     = $purchase->purchase_number;
        if(is_null($finishedDate))
        {
            $finishedDate   = '';
        }
        //采购单关联的供应商
        $sellerCompanyId    = $purchase->supplier_id;
        $where              = ['id'=>$sellerCompanyId];
        $sellerCompany      = SellerCompany::getInfo($where);
        if($sellerCompany){
            $imgPath            = Func::getImgUrlById($sellerCompany->img_id);
            $seller             = [
                'id'=>$sellerCompany->id,
                'title'=>$sellerCompany->title,
                'contact_mobile'=>$sellerCompany->contact_mobile,
                'img_path'=>$imgPath,
                'purchase_number'=>$purchaseNumber,
            ];
        }else{
            $seller             = [
                'id'=>0,
                'title'=>'---',
                'contact_mobile'=>'',
                'img_path'=>'',
                'purchase_number'=>'',
            ];
        }

        //采购单关联的材料列表
        $productData        = $this->getPurchaseProductList($purchaseId);
        $lists              = $productData['lists'];
        $totalMoney         = $productData['total_money'];
        //24=>'验收入库',//仓库给采购发消息4348
        //25=>'验收入库',//采购给财务发消息4349
        switch ($type)
        {
            case 24:
                break;
            case 25:
                break;
            default:
                xThrow(ERR_UNKNOWN);
        }

        //增加人民币符号&保留2位小数
        $totalMoney = "¥".sprintf("%.2f",$totalMoney);

        $result             = [
            'type'=>$type,
            'seller'=>$seller,
            'lists'=>$lists,
            'total_money'=>$totalMoney,
            'purchase_number'=>$purchaseNumber,
            'finished_date'=>$finishedDate,
        ];
        return $result;
    }
    //取采购单相关联的材料列表,包括总金额
    private function getPurchaseProductList($purchaseId)
    {
        $purchaseProductList= PurchaseMaterial::where('purchase_id',$purchaseId)->get();
        $lists              = $productIdArr = [];
        $totalMoney         = 0;
        foreach($purchaseProductList as $key=>$val)
        {
            $valMaterialId  = $val['material_id'];
            $valNum         = $val['num'];
            $valPrice       = $val['price'];
            $money          = $valNum * $valPrice;
            $temp           = [
                'id'=>$valMaterialId,
                'num'=>'×'.$valNum,
//                'price'=>'¥'.$valPrice,
//                'money'=>'¥'.$money,
                'product_name'=>'',
                'img_path'=>'',
                'first_text'=>'',
                'second_text'=>'',
                'third_text'=>'',
            ];

            //增加人民币符号&保留2位小数
            $temp['price'] = "¥".sprintf("%.2f",$valPrice);
            $temp['money'] = "¥".sprintf("%.2f",$money);

            $totalMoney     += $money;
            $lists[]        = $temp;
            $productIdArr[] = $valMaterialId;
        }
        if(!empty($productIdArr))
        {
            $where              = ['ygt_product.id'=>['in',$productIdArr]];
            $limit              = $offset = '';
            $productList        = Product::getListByJoin($where,$limit,$offset)->toArray();

            $assemblageMaterialIdArr = [];
            foreach ($productList as $tmpProductRow){
                $assemblageMaterialIdArr[] = $tmpProductRow['assemblage_material_id'];
            }

            //取材料的自定义属性值
            $where              = ['assemblage_material_id'=>['in',$assemblageMaterialIdArr]];
            $customFieldsArr    = ProductFields::getTransformListToArr($where);

            //过滤计量属性
            $tmpArr = $customFieldsArr;
            foreach ($tmpArr as $tmpK => $tmpV){
                foreach ($tmpV as $tmpKey => $tmpValue){
                    if($tmpValue['is_compute']){
                        unset($customFieldsArr[$tmpK][$tmpKey]);
                        $customFieldsArr[$tmpK] = array_values($customFieldsArr[$tmpK]);//数组重新排序
                    }
                }
            }

            //转换列表
            $otherArr           = ['custom_fields_arr'=>$customFieldsArr];
            $productList        = Product::transformListByType($productList,$otherArr);

            $newLists           = [];
            foreach($lists as $key=>$val)
            {
                $productId      = $val['id'];
                $temp           = $val;
                $numText        = $temp['num'];
                foreach($productList as $k=>$v)
                {
                     $vProductId     = $v['id'];
                    if($productId == $vProductId)
                    {
                        $numText    .= $v['unit'];
                        $temp['product_name']= $v['product_name'];
                        $temp['seller_company_name']= $v['seller_company_name'];
                        $temp['customer_name']= $v['customer_name'];

                        $temp['img_path']= $v['image_path'];
                        $temp['first_text']= $v['first_text'];
                        $temp['second_text']= $v['second_text'];
                        $temp['third_text']= $v['third_text'];
                        $temp['custom_fields_text']= $v['custom_fields_text'];
                    }
                }
                $temp['num']    = $numText;
                $newLists[]     = $temp;
            }
            $lists              = empty($newLists) ? $lists : $newLists;
        }
        $result         = ['lists'=>$lists,'total_money'=>$totalMoney];
        return $result;
    }
}